#include "codeconfig.h"
#include "CTConfig.h"

#define MAIN_SECTION    "Global"

// int型
#define GETINT(name, value) \
	value = cfg.GetInt(MAIN_SECTION, name, &iRet); \
	if (iRet) \
	{ \
	    CT_THROW(("[%s]%s failed %d", MAIN_SECTION, name, iRet)); \
	}

// char数组
#define GETSTR(name, value) \
	s = cfg.GetString(MAIN_SECTION, name, &iRet); \
	if (iRet) \
	{ \
	    CT_THROW(("[%s]%s failed %d", MAIN_SECTION, name, iRet)); \
	} \
	iRet = ct_snprintf(CT_STRSIZE(value), "%s", s.c_str()); \
	if (iRet < 0) \
	{ \
	    CT_THROW(("[%s]%s too long, over %d", MAIN_SECTION, name, sizeof(value))); \
	}

// string
#define GETSTRING(name, value) \
	value = cfg.GetString(MAIN_SECTION, name, &iRet); \
	if (iRet) \
	{ \
	    CT_THROW(("[%s]%s failed %d", MAIN_SECTION, name, iRet)); \
	}

CCodeConfig::CCodeConfig(void)
{
}

CCodeConfig::~CCodeConfig(void)
{
}

void CCodeConfig::LoadConfig(void)
{	
	CTConfig cfg;
	string s;
	int iRet = cfg.LoadConfig(FILE_CONFIG);
	if (iRet)
	{
		CT_THROW(("LoadConfig failed: %d", iRet));
	}

	GETSTR("EnpStreamKey", EnpStreamKey);
    GETSTR("EnpFrontEndSocket", EnpFrontEndSocket);
    GETSTR("EnpBackEndSocket", EnpBackEndSocket);
    GETINT("EnpStreamSize", EnpStreamSize);

	GETSTR("MainStreamKey", MainStreamKey);
	GETSTR("MainFrontEndSocket", MainFrontEndSocket);
	GETSTR("MainBackEndSocket", MainBackEndSocket);
	GETINT("MainStreamSize", MainStreamSize);

	LoadLogConfig();
}

void CCodeConfig::LoadLogConfig(void)
{
	CTConfig cfg;
	int iRet = cfg.LoadConfig(FILE_CONFIG);
	if (iRet)
	{
		CT_THROW(("LoadConfig failed: %d", iRet));
	}

	int iLogFileNum = 0, iLogFileSize = 0;
	GETINT("LogFileNum", iLogFileNum);
	GETINT("LogFileSize", iLogFileSize);
	CT_NLOG->Init(ENamed, NULL, FILE_NORMALLOG, iLogFileSize, iLogFileNum);
	CT_ELOG->Init(ENamed, NULL, FILE_ERRORLOG, iLogFileSize, iLogFileNum);
	CT_STAT->Init(ENamed, NULL, FILE_STATLOG, iLogFileSize, iLogFileNum);
	CT_STAT->SetFormat(ETime|ENewLine);

	// 设置format
	string str;
	GETSTRING("LogFormat", str)
	CT_NLOG->SetFormatByStr(str.c_str());
	CT_ELOG->SetFormatByStr(str.c_str());

	// 设置filter
	GETSTRING("LogFilter", str)
	CT_NLOG->SetFilterByStr(str.c_str());
	CT_ELOG->SetFilterByStr(str.c_str());

	CT_INFO(("LogFormat=%d LogFilter=%d", CT_NLOG->GetFormat(), CT_NLOG->GetFilter()));
}

void CCodeConfig::ReloadConfig(void)
{
	  LoadLogConfig();
}

/*
#ifndef WIN32
#include <sys/types.h>
#include <sys/ipc.h>
#endif

void CCodeConfig::Ftok(char * pszPathName, size_t iLen)
{
//#ifndef WIN32
	key_t iKey = ftok(pszPathName, 0);
	if (iKey == -1)
	{
		CT_THROW(("ftok(%s) failed %d", pszPathName, CT_ERRNO));
	}

	ct_snprintf(pszPathName, iLen, "%d", iKey);
//#endif
}
*/

